package cn.hd01.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hd01.repository.ProductRepository;
import cn.hd01.repository.entity.Product;
import cn.hd01.service.ProductService;

@Service
public class ProductServiceImpl extends BaseServiceImpl<Product, Integer> implements ProductService {

	private ProductRepository repository;
	
	@Autowired
	public ProductServiceImpl(ProductRepository repository) {
		super(repository);
		this.repository = repository;
	}

	@Override
	public int updateProductStatus(Integer id, String status) {
		int count = repository.updateProductStatus(status, id);
		return count;
	}

	@Override
	public int updateProduct(Product product) {
		int count = 0 ;
		if(StringUtils.isEmpty(product.getParentId())){
			count = repository.updateProduct(product.getName(), product.getProductDesc(),product.getPrice().doubleValue(), product.getId());
		}else{
			count = repository.updateProduct(product.getName(), product.getProductDesc(),product.getPrice().doubleValue(), product.getId(),product.getParentId());
		}
		return count;
	}
	
	@Override
	public Page<Product> findAll(final Product product, Pageable pageable) {
		if (product == null) {
			return repository.findAll(pageable);
		}

		return repository.findAll(Specifications.where(new Specification<Product>() {
			@Override
			public Predicate toPredicate(Root<Product> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();

				if (StringUtils.hasText(product.getName())) {
					predicates.add(cb.like(r.get("name").as(String.class), "%" + product.getName() + "%"));
				}
				
				if(product.getParentId() != null){
					predicates.add(cb.equal(r.get("parentId").as(Integer.class), product.getParentId()));
				}
				
				return cb.and(predicates.toArray(new Predicate[] {}));
			}
		}), pageable);
		
	}

	@Override
	public List<Product> findProductList() {
		return repository.findProductList();
	}

	@Override
	public List<Product> findParentProductList() {
		return repository.findParentProductList();
	}

}
